package com.jain.webcore.servlet;

import com.jain.webcore.database.JdbcUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * The database query servlet.
 */
@WebServlet("/Query")
public class QueryServlet extends BaseServlet {

    /**
     * Default constructor.
     */
    public QueryServlet() {
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request,
                          HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/x-javascript");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        String sql = new String(request.getParameter("sql").getBytes("iso-8859-1"), "utf-8");
        String result = null;

        if (sql != null) {

            JdbcUtils jdbcUtils = new JdbcUtils();
            jdbcUtils.getConnection();

            result = jdbcUtils.queryJsonString(sql);
            jdbcUtils.releaseConnect();
        }

        doResponse(response, result);
    }

}
